//
// Created by leisurexi on 12/6/20.
// peek_recv.c
//
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define BUF_SIZE 30

int server_sock;
int client_sock;

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    struct sockaddr_in server_addr, client_addr;
    int str_len;
    socklen_t client_addr_len;
    char buf[BUF_SIZE];
    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]);
        exit(1);
    }

    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    if (bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
        error_handling("bind() error");
    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");

    client_addr_len = sizeof(client_addr);
    client_sock = accept(server_sock, (struct sockaddr *) &client_addr, &client_addr_len);

    while (1) {
        str_len = recv(client_sock, buf, BUF_SIZE, MSG_PEEK | MSG_DONTWAIT);
        if (str_len > 0)
            // It's means has data for read.
            break;
    }

    buf[str_len] = 0;
    printf("Buffering %d bytes: %s \n", str_len, buf);

    str_len = recv(client_sock, buf, BUF_SIZE, 0);
    buf[str_len] = 0;
    printf("Read again: %s \n", buf);
    close(client_sock);
    close(server_sock);
    return 0;
}
